//
//  QRCodeScanVC.swift
//  EyesCare
//
//  Created by PMC on 2018/12/21.
//  Copyright © 2018年 qdsg. All rights reserved.
//

import UIKit
import HandyJSON

enum ECQrCodeScanFrom {
    case faceCollection  // 人脸采集
    case eyeChart        // 视力表
    case scan            // 扫一扫
}

class QRCodeScanVC: UIViewController {
    
    private lazy var scanView = QRCodeScanView(frame: self.view.bounds)
    private var scanManager: QRCodeManager?
    
    var scanFrom: ECQrCodeScanFrom = .scan {
        didSet {
            signLabel.isHidden = scanFrom != .eyeChart
        }
    }
    
    var handlerResult: ((_ jsonStr: String?, _ scanFrom: ECQrCodeScanFrom) -> Void)?
    
    private lazy var signLabel: UILabel = {
        let label = UILabel()
        label.text = "请扫描视力表设备上的二维码"
        label.textColor = UIColor.white
        label.font = UIFont.regular(18.0)
        label.textAlignment = .center
        label.isHidden = true
        return label
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavBar()
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .clear
            appearance.shadowColor = .clear
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
        }else{
            navigationController?.navigationBar.setBackgroundImage(UIImage(color: .clear), for: .default)
            
        }
        authCamera()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.textDark]
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .clear
            appearance.shadowColor = .clear
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
        }else{
            navigationController?.navigationBar.setBackgroundImage(UIImage(color: .clear), for: .default)
            
        }
        scanManager?.stopScanning()
    }
    
    private func setupUI() {
        scanView.autoresizingMask = .flexibleHeight
        view.addSubview(scanView)
        view.addSubview(signLabel)
        signLabel.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-(bottomSafeH + 30))
            make.centerX.equalToSuperview()
        }
    }
    
    private func setupNavBar() {
        navigationItem.title = "扫二维码"
        navigationItem.leftBarButtonItem = nil
        navigationItem.hidesBackButton = true
        let leftItem = UIBarButtonItem(imageName: "back_arrow_white", target: self, action: #selector(popBack))
        let spaceItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        spaceItem.width = -10.0
        navigationItem.leftBarButtonItems = [spaceItem, leftItem]
    }
    
    @objc private func popBack() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func openPhoto() {
        Permissions.authorizeAlbum { (isGranted) in
            if isGranted {
                self.scanManager?.presentPhotoLibrary(withRootVc: self) { [weak self] (result) in
                    self?.handleScanValue(jsonStr: result)
                }
            } else {
                AlertTool.showAlert(self,
                                    message: "需要访问您的相册\n请启用相册-设置-隐私-相册",
                                    sureTitle: "去打开",
                                    cancelTitle: "取消",
                                    type: .double,
                                    sureHandler: { (action) in
                    SettingTools.openAppSetting()
                })
            }
        }
    }
}

extension QRCodeScanVC {
    private func startScanning() {
        self.scanManager?.startScanning(callback: { [weak self] (result) in
            self?.handleScanValue(jsonStr: result)
            }, autoStop: true)
    }
    
    private func authCamera() {
        Permissions.authorizeCamera { (isGranted) in
            if isGranted {
                self.scanManager = QRCodeManager(scanView: self.scanView, completion: { [weak self] in
                    self?.startScanning()
                })
            } else {
                AlertTool.showAlert(self,
                                    message: "需要访问您的相机\n请启用相机-设置-隐私-相机",
                                    sureTitle: "去打开",
                                    cancelTitle: "取消",
                                    type: .double,
                                    sureHandler: { (action) in
                    SettingTools.openAppSetting()
                })
            }
        }
    }
    
    private func handleScanValue(jsonStr: String?) {
        navigationController?.popViewController(animated: true)
        handlerResult?(jsonStr, scanFrom)
    }
}
